<template>
  <el-dialog
    title="电子材料明细"
    :visible.sync="visible"
    width="1200px"
    :close-on-click-modal="false"
    :style="{ zIndex: 1000 }"
    @close="handleClose"
  >
    <div class="app-container">
      <!--工具栏-->
      <div class="head-container">
        <!--表格渲染-->
        <content-block label="电子材料明细">
          <el-table ref="table" v-loading="crud.loading" :height="550" :data="crud.data" size="small" style="width: 100%;" border :header-cell-style="{background:'#f5f7fa', color:'#777'}">
            <el-table-column type="index" label="序号" width="50" align="center" header-align="center" fixed="left" />
            <el-table-column prop="aac001" label="个人编号" fixed="left" width="220px" align="center" header-align="center" />
            <el-table-column prop="aac003" label="姓名" width="150px" align="center" header-align="center" />
            <el-table-column prop="aaa121" label="业务类型" width="200px" align="center" header-align="center" :formatter="formatter" />
            <el-table-column width="150px" label="原材料" align="center" header-align="center">
              <template slot-scope="scope">
                <div style="width: 150px; height: 100px; position: relative;">
                  <!-- 图片 -->
                  <img
                    v-if="scope.row.filetype === 'image'"
                    :src="scope.row.base64"
                    style="
                  width: 100%;
                  height: 100%;
                  object-fit: contain;"
                  >
                  <!-- PDF -->
                  <embed
                    v-else-if="scope.row.filetype === 'pdf'"
                    :src="pdfUrl(scope.row)"
                    type="application/pdf"
                    style="width: 100%; height: 100%;"
                  >
                  <!-- 透明点击层 -->
                  <div
                    style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer"
                    @click="handlePreview(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <!--          <el-table-column prop="id" label="材料编号" width="220px" align="center" header-align="center" />-->
            <el-table-column prop="filename" label="文件名称" width="300px" align="center" header-align="center" show-overflow-tooltip :formatter="formatterName" />
            <el-table-column prop="filesize" label="文件大小" width="150px" align="center" header-align="center" show-overflow-tooltip />
            <el-table-column v-if="false" prop="filepath" label="材料路径" width="250px" align="center" header-align="center" />
            <el-table-column prop="aae036" label="创建时间" width="200px" align="center" header-align="center" />
            <el-table-column
              label="操作"
              width="100"
              fixed="right"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handlePreview(scope.row)"
                >预览</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination />
        </content-block>
        <!--      </el-card>-->
        <!-- 新增材料对话框 -->
        <material-add-dialog
          :visible.sync="addDialogVisible"
          :person-list="personList"
          :business-type-options="businessTypeOptions"
          append-to-body
          @gbCallBack="gbCallBack"
          @uploadSuccessBack="uploadSuccessBack"
          @refresh="handleRefresh"
        />
        <!-- 预览对话框 -->
        <material-preview-dialog
          :visible.sync="previewDialogVisible"
          :material="currentMaterial"
          @gbCallBack="gbCallBack"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script>
import MaterialAddDialog from './MaterialAddDialog'
import MaterialPreviewDialog from './MaterialPreviewDialog'
import ContentBlock from '@/components/labers/contentBlock'
import CRUD, { crud, header, presenter } from '@crud/crud'
import fileUpload from '@/views/ynsb_comm/fileupload/fileUpload'
import pagination from '@crud/Pagination'
import moment from 'moment'
import commUtil from '@/views/ynsb_comm/comm/util/commUtil'

export default {
  name: 'FileDetail',
  components: {
    ContentBlock,
    MaterialAddDialog,
    pagination,
    MaterialPreviewDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    currentMaterialHz: {
      type: Object,
      default: () => ({})
    }
  },
  mixins: [presenter(), header(), crud()],
  cruds() {
    return CRUD({ title: '电子材料录入', url: '/api/electronic-material/list', idField: 'id', sort: 'id,desc', crudMethod: { ...fileUpload }})
  },
  // 数据字典
  dicts: ['aaa121'],
  data() {
    return {
      queryForm: {
        aac001: '',
        aac003: '',
        aaa121: ''
      },
      materialList: [],
      personList: [
      ],
      businessTypeOptions: [
      ],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      addDialogVisible: false,
      previewDialogVisible: false,
      currentMaterial: null
    }
  },
  created() {
  },
  methods: {
    moment,
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      // this.crud.params = {
      //   aac001: this.currentMaterialHz.aac001,
      //   materialid: this.currentMaterialHz.id,
      //   queryType: '1',
      //   aaa121: this.currentMaterialHz.aaa121
      // }
      return true
    },
    pdfUrl(row) {
      // 假设 row.content 是 PDF 文件的 ArrayBuffer 或 Blob 对象
      // 如果后端传的是base64，需要先转换为Blob
      let blob
      if (row.content instanceof Blob) {
        blob = row.content
      } else if (row.base64) {
        // 如果只有base64，则需要转换
        const byteCharacters = atob(row.base64.split(',')[1])
        const byteNumbers = new Array(byteCharacters.length)
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i)
        }
        const byteArray = new Uint8Array(byteNumbers)
        blob = new Blob([byteArray], { type: 'application/pdf' })
      } else {
        // 如果没有可用数据，返回空字符串或处理错误
        return ''
      }
      return URL.createObjectURL(blob)
    },
    getFileDetail() {
      this.crud.params = {
        aac001: this.currentMaterialHz.aac001,
        materialid: this.currentMaterialHz.id,
        queryType: '1',
        aaa121: this.currentMaterialHz.aaa121
      }
      console.log(this.currentMaterialHz, 'this.currentMaterialHz')
      this.crud.pageChangeHandler(1)
    },
    handleClose() {
      this.visible = false
      this.$emit('gbCallBack')
    },
    personRpcCallBack(item) {
      this.queryForm.aac001 = item.aac001
      this.queryForm.aac003 = item.aac003
    },
    // 查询材料列表
    fetchMaterialList() {
      this.crud.params = {
        aac001: this.queryForm.aac001,
        aaa121: this.queryForm.aaa121
      }
      this.crud.pageChangeHandler(1)
    },
    // 处理查询
    handleQuery() {
      this.previewDialogVisible = false
      this.addDialogVisible = false
      this.fetchMaterialList()
    },

    // 重置查询
    resetQuery() {
      this.queryForm = {
        aac001: '',
        aaa121: ''
      }
      this.$refs.personRpc.restAac001('')
      this.handleQuery()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchMaterialList()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchMaterialList()
    },

    // 显示新增对话框
    showAddDialog() {
      this.addDialogVisible = true
    },

    // 预览材料
    handlePreview(row) {
      this.currentMaterial = row
      row.aae036_yw = moment(row.aae036).format('YYYY-MM-DD')
      // 查询图片base64
      // 假设查询的数据
      // fileupload.getBase64({ ...row }).then(res => {
      this.currentMaterial.base64 = row.base64
      this.previewDialogVisible = true
      // })
    },

    // 刷新列表
    handleRefresh() {
      this.fetchMaterialList()
    },
    // 关闭新增
    gbCallBack() {
      this.previewDialogVisible = false
      this.addDialogVisible = false
    },
    uploadSuccessBack() {
      this.addDialogVisible = false
      this.fetchMaterialList()
    },
    formatter(row, column, cellValue) {
      // 根据 aae140 的值进行转码
      const key = column.property
      const data = this.dict[key]
      if (data.length === 0) {
        return cellValue
      }
      const dataList = data.filter(item => item.value === cellValue)
      console.log(dataList, 'data')
      if (dataList !== null && dataList !== [] && dataList !== undefined && dataList.length > 0) {
        return dataList[0].label
      } else {
        return cellValue
      }
    },
    formatterName(row, column, cellValue) {
      if (commUtil.isNull(cellValue)) {
        return cellValue
      } else {
        const extension = cellValue.split('_').pop().toLowerCase()
        // 根据 aae140 的值进行转码
        return extension
      }
    }
  }
}
</script>

<style scoped>
.material-management {
  padding: 20px;
}

.box-card {
  max-width: 1200px;
  margin: 0 auto;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
